'use strict';
// 引入package封装类
import Package from '@breeze-cli-dev/package';
import log from '@breeze-cli-dev/log';
import path from 'path';
import cp from 'child_process';
import fs from 'fs';
// pathToFileURL保证window下的路径可以被识别
import { pathToFileURL } from 'url';
const SETTINGS = {
  // init: '@breeze-cli-dev/init'
  init: '@imooc-cli/init'
};
const CACHE_DIR = 'dependencies';
async function exec() {
  // const execPackage = new Package()
  let targetPath = process.env.CLI_TARGET_PATH;
  const homePath = process.env.CLI_HOME_PATH;

  const cmdObj = arguments[arguments.length - 1];
  const cmdName = cmdObj.name();
  let storeDir = '';
  let pkg;
  const packageName = SETTINGS[cmdName];
  const packageVersion = 'latest'
  try {
    if (!targetPath) {
      targetPath = path.resolve(homePath, CACHE_DIR)
      storeDir = path.resolve(targetPath, 'node_modules')
      log.verbose('targetPath', targetPath);
      log.verbose('storeDir', storeDir);
      pkg = new Package({
        targetPath,
        storeDir,
        packageName,
        packageVersion
      });
      if (pkg.exists()) {
        // await pkg.update()
        console.log('准备去更新了')
        await pkg.update()
      } else {
        console.log('准备去重新下载了')
        await pkg.install()
      }
      
    } else {
      pkg = new Package({
        targetPath,
        storeDir,
        packageName,
        packageVersion
      });
    }
    const filePath =  pkg.getRootFilePath()
    import(pathToFileURL(filePath)).then(res => {
      if (res) {
        try {
          res.default.call(null, Array.from(arguments))
        } catch (error) {
          log.error(error.message)
        }
      }
    })
    console.log('exec命令执行了');
  } catch (error) {
    log.error(error.message)
  }
}
export {
  exec
}